#include "unp.h"
#include "client.h"

Client *clientList = NULL;
Client *freeList = NULL;

/* Create a client and inser it to clientList
 * Returns: pointer to client node
 *	    NULL if couldn't create (Connection should be closed and fejected)
 *
 */
Client *
createClient(int connfd) {
	Client *c;
	int i, j;
	int count = 1;

	if (freeList == NULL) {
		// if freeList is empty, allocate memory for a client.
		if ((c = (Client *) malloc(sizeof(Client))) == NULL)
			return (NULL); // Not enough memory. return NULL
	} else {
		// Get a client node from freeList. Allocated memory is reused.
		c = freeList;
		freeList = freeList->next;
	}
	// Initialize the client node
	c->connfd = connfd;
	c->user[0] = '\0';
	c->buf[0] = '\0';
	for (i = 0; i < 5; i++) {
		for (j = 0; j < 5; j++) {
			c->bingo[i][j] = count;
			count++;
		}
	}
	count = 0;
	c->next = clientList; // Insert the client node in front of clientList
	clientList = c;
	return (c);	// returns pointer to the client node
}

/*
 *	Destroy the client. Just put into freeList for reuse later
 */
void destroyClient(Client *c) {
	Client *cur, **pre;

	// remove the client from clientList
	for (pre = &clientList, cur = clientList; (cur != c);
			pre = &(cur->next), cur = cur->next)
		; // find predecessor
	*pre = c->next;	//remove the client

	// insert it to the front of freeList
	c->next = freeList;
	freeList = c;
}

/* Get the client of connected socket fd
 * Returns: pointer to client if found
 *				NULL if not found
 */
Client *
getClient(int fd) {
	Client *client;

	for (client = clientList; client != NULL; client = client->next) {
		if (client->connfd == fd)
			return (client);
	}
	return (NULL);
}

Client *
getClientList() {
	return (clientList);
}

//init
//void initCount(int **bingo) {
//	int i, j;
//	int count = 1;
//	for (i = 0; i < 5; i++) {
//		for (j = 0; j < 5; j++) {
//			printf("11111\n");
//			bingo[i][j] = count;
//			printf("11111\n");
//			count++;
//		}
//	}
//}
